<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>二手易购 - 购物车</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    /* 全局样式 */
    :root {
      --primary: #1a1a1a;
      --secondary: #333333;
      --accent: #666666;
      --light: #f5f5f5;
      --white: #ffffff;
      --dark: #000000;
      --light-gray: #e0e0e0;
      --medium-gray: #999999;
      --success: #28a745;
      --error: #dc3545;
      --warning: #ffc107;
      --shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
      --transition: all 0.2s ease;
    }

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
    }

    body {
      background: linear-gradient(135deg, #f8f9fa 0%, #eef0f2 100%);
      color: var(--dark);
      min-height: 100vh;
      padding-bottom: 80px;
    }

    /* 顶部导航栏 */
    .navbar {
      background: var(--white);
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
      padding: 12px 30px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: sticky;
      top: 0;
      z-index: 1000;
    }

    .logo {
      display: flex;
      align-items: center;
      transform-origin: left center;
    }

    .logo:hover {
      transform: scale(1.03);
    }

    .logo h1 {
      font-size: 22px;
      font-weight: 700;
      color: var(--dark);
      margin-left: 8px;
      letter-spacing: -0.5px;
    }

    .logo i {
      font-size: 24px;
      color: var(--accent);
    }

    .search-container {
      flex: 1;
      max-width: 550px;
      margin: 0 15px;
      position: relative;
    }

    .search-container input {
      width: 100%;
      padding: 12px 20px;
      border: 1px solid var(--light-gray);
      border-radius: 25px;
      font-size: 14px;
      transition: var(--transition);
      background-color: var(--white);
      color: var(--dark);
      outline: none;
      padding-right: 45px;
      box-shadow: 0 3px 8px rgba(0, 0, 0, 0.05);
    }

    .search-container input:focus {
      box-shadow: 0 3px 12px rgba(0, 0, 0, 0.1);
      border-color: var(--accent);
    }

    .search-container button {
      position: absolute;
      right: 8px;
      top: 50%;
      transform: translateY(-50%);
      background: none;
      border: none;
      color: var(--accent);
      cursor: pointer;
      font-size: 16px;
    }

    .nav-links {
      display: flex;
      gap: 20px;
    }

    .nav-link {
      display: flex;
      flex-direction: column;
      align-items: center;
      text-decoration: none;
      color: var(--dark);
      font-size: 13px;
      transition: var(--transition);
      position: relative;
      padding: 4px 8px;
      border-radius: 6px;
    }

    .nav-link i {
      font-size: 18px;
      margin-bottom: 3px;
    }

    .nav-link:hover {
      color: var(--accent);
      background-color: rgba(0, 0, 0, 0.03);
    }

    .nav-link .badge {
      position: absolute;
      top: -4px;
      right: -4px;
      background-color: var(--error);
      color: var(--white);
      border-radius: 50%;
      width: 18px;
      height: 18px;
      font-size: 11px;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 2px 4px rgba(0,0,0,0.15);
    }

    .user-menu {
      display: flex;
      align-items: center;
      cursor: pointer;
      position: relative;
    }

    .user-avatar {
      width: 38px;
      height: 38px;
      border-radius: 50%;
      background: linear-gradient(135deg, #e0e0e0, #f0f0f0);
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      margin-left: 12px;
      box-shadow: 0 2px 6px rgba(0,0,0,0.1);
    }

    .user-avatar img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .user-avatar i {
      font-size: 18px;
      color: var(--accent);
    }

    .dropdown-menu {
      position: absolute;
      top: 50px;
      right: 0;
      background: var(--white);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
      border-radius: 10px;
      width: 180px;
      overflow: hidden;
      display: none;
      z-index: 1000;
    }

    .dropdown-menu.show {
      display: block;
    }

    .dropdown-item {
      padding: 10px 16px;
      display: flex;
      align-items: center;
      text-decoration: none;
      color: var(--dark);
      transition: var(--transition);
      position: relative;
      font-size: 14px;
    }

    .dropdown-item:hover {
      background-color: rgba(0, 0, 0, 0.05);
      padding-left: 20px;
    }

    .dropdown-item:hover::before {
      content: "";
      position: absolute;
      left: 0;
      top: 0;
      height: 100%;
      width: 3px;
      background: var(--dark);
    }

    .dropdown-item i {
      margin-right: 8px;
      width: 18px;
      text-align: center;
      font-size: 14px;
    }

    .divider {
      height: 1px;
      background-color: var(--light-gray);
      margin: 4px 0;
    }

    /* 内容区域 */
    .container {
      max-width: 1300px;
      margin: 25px auto;
      padding: 0 20px;
    }

    /* 页面标题 */
    .page-title {
      text-align: center;
      margin: 35px 0 45px;
      position: relative;
    }

    .page-title h2 {
      font-size: 32px;
      font-weight: 800;
      letter-spacing: -1px;
      margin-bottom: 12px;
    }

    .page-title p {
      font-size: 17px;
      color: var(--medium-gray);
      max-width: 550px;
      margin: 0 auto;
      line-height: 1.6;
    }

    .page-title::after {
      content: '';
      position: absolute;
      bottom: -18px;
      left: 50%;
      transform: translateX(-50%);
      width: 90px;
      height: 3px;
      background: var(--dark);
      border-radius: 2px;
    }

    /* 购物车容器 */
    .cart-container {
      display: flex;
      gap: 30px;
      margin-bottom: 50px;
    }

    /* 商品列表 */
    .cart-items {
      flex: 1;
      background: var(--white);
      border-radius: 16px;
      box-shadow: var(--shadow);
      overflow: hidden;
    }

    .cart-header {
      display: flex;
      align-items: center;
      padding: 20px;
      border-bottom: 1px solid var(--light-gray);
      background: linear-gradient(to right, #f9f9f9, #f0f0f0);
    }

    .cart-header h3 {
      font-size: 20px;
      font-weight: 700;
      color: var(--dark);
      flex: 1;
    }

    .cart-header button {
      background: none;
      border: none;
      color: var(--accent);
      cursor: pointer;
      font-size: 15px;
      font-weight: 600;
      display: flex;
      align-items: center;
      gap: 6px;
      transition: var(--transition);
    }

    .cart-header button:hover {
      color: var(--error);
      transform: translateX(3px);
    }

    .cart-header button i {
      font-size: 16px;
    }

    /* 空购物车 */
    .empty-cart {
      padding: 60px 30px;
      text-align: center;
    }

    .empty-cart i {
      font-size: 80px;
      color: var(--light-gray);
      margin-bottom: 20px;
      opacity: 0.5;
    }

    .empty-cart h4 {
      font-size: 24px;
      color: var(--dark);
      margin-bottom: 15px;
      font-weight: 700;
    }

    .empty-cart p {
      color: var(--medium-gray);
      margin-bottom: 30px;
      max-width: 400px;
      margin-left: auto;
      margin-right: auto;
    }

    .empty-cart .btn {
      padding: 12px 30px;
      border-radius: 8px;
      background: var(--dark);
      color: var(--white);
      border: none;
      font-weight: 600;
      cursor: pointer;
      transition: var(--transition);
      display: inline-block;
      text-decoration: none;
    }

    .empty-cart .btn:hover {
      background: #111;
      transform: translateY(-3px);
      box-shadow: 0 8px 18px rgba(0,0,0,0.15);
    }

    /* 购物车项目 */
    .cart-item {
      display: flex;
      padding: 20px;
      border-bottom: 1px solid var(--light-gray);
      transition: var(--transition);
      position: relative;
    }

    .cart-item:hover {
      background-color: rgba(0, 0, 0, 0.02);
    }

    .item-image {
      width: 120px;
      height: 120px;
      border-radius: 10px;
      overflow: hidden;
      background: linear-gradient(135deg, #f0f0f0, #e0e0e0);
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      margin-right: 20px;
    }

    .item-image img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .item-details {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      padding: 5px 0;
    }

    .item-info {
      margin-bottom: 15px;
    }

    .item-name {
      font-size: 18px;
      font-weight: 700;
      margin-bottom: 8px;
      color: var(--dark);
    }

    .item-category {
      font-size: 14px;
      color: var(--medium-gray);
      margin-bottom: 10px;
    }

    .item-stock {
      font-size: 14px;
      color: var(--success);
      font-weight: 600;
    }

    .item-actions {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .item-price {
      font-size: 20px;
      font-weight: 800;
      color: var(--dark);
    }

    .item-quantity {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .quantity-btn {
      width: 36px;
      height: 36px;
      background: var(--light-gray);
      border: none;
      border-radius: 8px;
      font-size: 18px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s ease;
      box-shadow: 0 2px 6px rgba(0,0,0,0.1);
    }

    .quantity-btn:hover {
      background: var(--accent);
      color: white;
      transform: translateY(-2px);
      box-shadow: 0 4px 10px rgba(0,0,0,0.15);
    }

    .quantity-btn:disabled {
      background-color: #f0f0f0;
      color: #ccc;
      cursor: not-allowed;
      transform: none;
      box-shadow: none;
    }

    .quantity-input {
      width: 55px;
      height: 36px;
      text-align: center;
      border: 1px solid var(--light-gray);
      border-radius: 8px;
      font-size: 16px;
      font-weight: 600;
      box-shadow: inset 0 1px 4px rgba(0,0,0,0.05);
    }

    .remove-btn {
      position: absolute;
      top: 20px;
      right: 20px;
      background: none;
      border: none;
      color: var(--medium-gray);
      cursor: pointer;
      font-size: 18px;
      transition: var(--transition);
    }

    .remove-btn:hover {
      color: var(--error);
      transform: scale(1.1);
    }

    /* 购物车摘要 */
    .cart-summary {
      width: 380px;
      background: var(--white);
      border-radius: 16px;
      box-shadow: var(--shadow);
      padding: 25px;
      align-self: flex-start;
      position: sticky;
      top: 100px;
    }

    .summary-title {
      font-size: 22px;
      font-weight: 800;
      margin-bottom: 25px;
      padding-bottom: 15px;
      border-bottom: 1px solid var(--light-gray);
      letter-spacing: -0.5px;
    }

    .summary-row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 15px;
      padding-bottom: 15px;
      border-bottom: 1px dashed var(--light-gray);
    }

    .summary-row:last-child {
      border-bottom: none;
      margin-bottom: 0;
      padding-bottom: 0;
    }

    .summary-label {
      color: var(--medium-gray);
      font-size: 16px;
      font-weight: 500;
    }

    .summary-value {
      color: var(--dark);
      font-size: 16px;
      font-weight: 600;
      text-align: right;
    }

    .summary-total {
      font-size: 20px;
      font-weight: 800;
      color: var(--dark);
    }

    .summary-value.total {
      font-size: 22px;
      font-weight: 800;
    }

    .coupon-section {
      margin: 25px 0;
      padding: 20px;
      background: linear-gradient(135deg, #f8f9fa, #f0f2f4);
      border-radius: 12px;
      border: 1px solid rgba(0,0,0,0.05);
    }

    .coupon-title {
      font-size: 17px;
      font-weight: 700;
      margin-bottom: 15px;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .coupon-title i {
      color: var(--accent);
    }

    .coupon-input {
      display: flex;
      gap: 10px;
      margin-bottom: 15px;
    }

    .coupon-input input {
      flex: 1;
      padding: 12px 15px;
      border: 1px solid var(--light-gray);
      border-radius: 8px;
      font-size: 15px;
      outline: none;
    }

    .coupon-input button {
      padding: 0 20px;
      background: var(--dark);
      color: var(--white);
      border: none;
      border-radius: 8px;
      font-weight: 600;
      cursor: pointer;
      transition: var(--transition);
    }

    .coupon-input button:hover {
      background: #111;
      transform: translateY(-2px);
    }

    .coupon-hint {
      font-size: 14px;
      color: var(--medium-gray);
    }

    .checkout-btn {
      width: 100%;
      padding: 16px 0;
      border-radius: 12px;
      background: var(--dark);
      color: var(--white);
      border: none;
      font-size: 18px;
      font-weight: 700;
      cursor: pointer;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10px;
      position: relative;
      overflow: hidden;
      box-shadow: 0 6px 18px rgba(0,0,0,0.15);
      margin-top: 20px;
    }

    .checkout-btn:hover {
      background: #111;
      transform: translateY(-3px);
      box-shadow: 0 10px 25px rgba(0,0,0,0.2);
    }

    .checkout-btn:disabled {
      background: var(--medium-gray);
      cursor: not-allowed;
      transform: none;
      box-shadow: none;
    }

    .continue-link {
      display: block;
      text-align: center;
      margin-top: 20px;
      color: var(--accent);
      text-decoration: none;
      font-weight: 600;
      transition: var(--transition);
    }

    .continue-link:hover {
      color: var(--dark);
      text-decoration: underline;
    }

    /* 响应式设计 */
    @media (max-width: 992px) {
      .cart-container {
        flex-direction: column;
      }

      .cart-summary {
        width: 100%;
      }
    }

    @media (max-width: 768px) {
      .cart-item {
        flex-direction: column;
      }

      .item-image {
        width: 100%;
        height: 200px;
        margin-right: 0;
        margin-bottom: 15px;
      }

      .item-actions {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
      }

      .item-price {
        margin-top: 10px;
      }
    }

    /* 浮动按钮 */
    .floating-btn {
      position: fixed;
      bottom: 30px;
      right: 30px;
      width: 65px;
      height: 65px;
      background: var(--dark);
      color: white;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 25px;
      box-shadow: 0 5px 22px rgba(0, 0, 0, 0.25);
      cursor: pointer;
      z-index: 100;
      transition: all 0.3s ease;
    }

    .floating-btn:hover {
      transform: scale(1.1);
      box-shadow: 0 8px 28px rgba(0, 0, 0, 0.3);
    }

    .floating-btn::after {
      content: "继续购物";
      position: absolute;
      top: -38px;
      left: 50%;
      transform: translateX(-50%);
      background: var(--dark);
      color: white;
      padding: 5px 12px;
      border-radius: 5px;
      font-size: 13px;
      white-space: nowrap;
      opacity: 0;
      transition: opacity 0.3s;
      font-weight: 500;
    }

    .floating-btn:hover::after {
      opacity: 1;
    }

    /* 加载动画 */
    .loader {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      text-align: center;
      padding: 50px 0;
    }

    .loader .spinner {
      width: 50px;
      height: 50px;
      border: 4px solid rgba(0, 0, 0, 0.1);
      border-radius: 50%;
      border-top-color: var(--dark);
      animation: spin 1.2s linear infinite;
      margin-bottom: 15px;
    }

    @keyframes spin {
      to { transform: rotate(360deg); }
    }

    /* 通知 */
    .notification {
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 15px 25px;
      border-radius: 10px;
      background-color: var(--success);
      color: white;
      font-weight: 600;
      box-shadow: 0 8px 25px rgba(0,0,0,0.15);
      z-index: 3000;
      font-size: 15px;
      display: none;
    }

    .notification.error {
      background-color: var(--error);
    }
  </style>
</head>
<body>
<!-- 顶部导航栏 -->
<nav class="navbar">
  <div class="logo">
    <i class="fas fa-recycle"></i>
    <h1>二手易购</h1>
  </div>

  <div class="nav-links">
    <a href="productPage.html" class="nav-link">
      <i class="fas fa-home"></i>
      <span>首页</span>
    </a>
    <a href="my-goods.html" class="nav-link">
      <i class="fas fa-box"></i>
      <span>我的商品</span>
    </a>
    <a href="orders.html" class="nav-link">
      <i class="fas fa-file-invoice"></i>
      <span>订单</span>
    </a>
    <a href="my-comments.html" class="nav-link">
      <i class="fas fa-comment-alt"></i>
      <span>评论</span>
    </a>
    <a href="#" class="nav-link active">
      <i class="fas fa-shopping-cart"></i>
      <span>购物车</span>
      <span class="badge" id="cartCount">0</span>
    </a>
  </div>

  <div class="user-menu" id="userMenu">
    <span id="usernameDisplay">游客</span>
    <div class="user-avatar">
      <i class="fas fa-user"></i>
    </div>
    <div class="dropdown-menu" id="dropdownMenu">
      <a href="#" class="dropdown-item" id="profileLink">
        <i class="fas fa-user-circle"></i>个人中心
      </a>
      <div class="divider"></div>
      <a href="#" class="dropdown-item" id="logoutLink">
        <i class="fas fa-sign-out-alt"></i>退出登录
      </a>
    </div>
  </div>
</nav>

<!-- 主内容区域 -->
<div class="container">
  <!-- 页面标题 -->
  <div class="page-title">
    <h2>我的购物车</h2>
    <p>查看并管理您已添加到购物车的商品</p>
  </div>

  <!-- 购物车容器 -->
  <div class="cart-container">
    <!-- 购物车商品列表 -->
    <div class="cart-items">
      <div class="cart-header">
        <h3 id="cartHeader">购物车商品 (加载中...)</h3>
        <button id="clearCartBtn">
          <i class="fas fa-trash-alt"></i> 清空购物车
        </button>
      </div>

      <div class="loader" id="cartLoader">
        <div class="spinner"></div>
        <p>正在加载购物车...</p>
      </div>

      <div id="cartItemsContainer">
        <!-- 购物车项目将通过JS动态加载 -->
      </div>

      <div class="empty-cart" id="emptyCart" style="display: none;">
        <i class="fas fa-shopping-cart"></i>
        <h4>您的购物车是空的</h4>
        <p>您还没有添加任何商品到购物车，快去挑选心仪的商品吧！</p>
        <a href="productPage.html" class="btn">去购物</a>
      </div>
    </div>

    <!-- 购物车摘要 -->
    <div class="cart-summary">
      <h3 class="summary-title">订单摘要</h3>

      <div class="summary-row">
        <div class="summary-label">商品小计</div>
        <div class="summary-value" id="subtotal">¥0.00</div>
      </div>

      <div class="summary-row">
        <div class="summary-label">运费</div>
        <div class="summary-value">¥0.00</div>
      </div>

      <div class="summary-row">
        <div class="summary-label">折扣</div>
        <div class="summary-value">-¥0.00</div>
      </div>

      <div class="summary-row">
        <div class="summary-label">预估税费</div>
        <div class="summary-value">¥0.00</div>
      </div>

      <div class="summary-row">
        <div class="summary-label">总计</div>
        <div class="summary-value summary-total" id="total">¥0.00</div>
      </div>

      <button class="checkout-btn" id="checkoutBtn" disabled>
        <i class="fas fa-shopping-bag"></i> 结算购物车
      </button>

      <a href="productPage.html" class="continue-link">
        <i class="fas fa-arrow-left"></i> 继续购物
      </a>
    </div>
  </div>
</div>

<!-- 浮动按钮 -->
<div class="floating-btn" id="continueShoppingBtn">
  <i class="fas fa-arrow-left"></i>
</div>

<!-- 通知 -->
<div class="notification" id="notification"></div>

<script>
  // API 基础URL
  const API_BASE_URL = 'http://localhost:8080';

  // 用户信息
  let userInfo = JSON.parse(localStorage.getItem('userInfo')) || null;

  // DOM元素
  const cartItemsContainer = document.getElementById('cartItemsContainer');
  const cartHeader = document.getElementById('cartHeader');
  const cartLoader = document.getElementById('cartLoader');
  const emptyCart = document.getElementById('emptyCart');
  const clearCartBtn = document.getElementById('clearCartBtn');
  const checkoutBtn = document.getElementById('checkoutBtn');
  const subtotalElement = document.getElementById('subtotal');
  const totalElement = document.getElementById('total');
  const cartCount = document.getElementById('cartCount');
  const notification = document.getElementById('notification');
  const continueShoppingBtn = document.getElementById('continueShoppingBtn');

  // 初始化页面
  document.addEventListener('DOMContentLoaded', function() {
    // 更新用户信息显示
    updateUserInfo();

    // 获取购物车数据
    fetchCartData();

    // 设置事件监听器
    setupEventListeners();
  });

  // 更新用户信息显示
  function updateUserInfo() {
    if (userInfo) {
      document.getElementById('usernameDisplay').textContent = userInfo.username || '游客';
    } else {
      // 如果用户未登录，跳转到登录页
      window.location.href = 'login.html';
    }
  }

  // 设置事件监听器
  function setupEventListeners() {
    // 清空购物车按钮
    clearCartBtn.addEventListener('click', clearCart);

    // 结算按钮
    checkoutBtn.addEventListener('click', checkout);

    // 浮动按钮
    continueShoppingBtn.addEventListener('click', function() {
      window.location.href = 'productPage.html';
    });

    // 退出登录
    document.getElementById('logoutLink').addEventListener('click', function(e) {
      e.preventDefault();
      localStorage.removeItem('userInfo');
      window.location.href = 'login.html';
    });

    // 个人中心
    document.getElementById('profileLink').addEventListener('click', function(e) {
      e.preventDefault();
      window.location.href = 'profile.html';
    });
  }

  // 获取购物车数据
  function fetchCartData() {
    if (!userInfo) return;

    // 显示加载状态
    cartLoader.style.display = 'flex';
    cartItemsContainer.innerHTML = '';
    emptyCart.style.display = 'none';

    // 调用后端API获取购物车详情
    fetch(`${API_BASE_URL}/shoppingCart/details/${userInfo.userId}`)
            .then(response => {
              if (!response.ok) {
                throw new Error('获取购物车数据失败');
              }
              return response.json();
            })
            .then(cartItems => {
              // 渲染购物车商品
              renderCartItems(cartItems);

              // 更新购物车摘要
              updateCartSummary(cartItems);

              // 更新购物车数量
              updateCartCount(cartItems.length);

              // 隐藏加载状态
              cartLoader.style.display = 'none';
            })
            .catch(error => {
              console.error('获取购物车数据失败:', error);
              showNotification('获取购物车数据失败', true);
              cartLoader.style.display = 'none';
              emptyCart.style.display = 'block';
              cartHeader.textContent = '购物车商品 (0)';
            });
  }

  // 渲染购物车商品
  function renderCartItems(cartItems) {
    cartItemsContainer.innerHTML = '';

    if (cartItems.length === 0) {
      emptyCart.style.display = 'block';
      cartHeader.textContent = '购物车商品 (0)';
      checkoutBtn.disabled = true;
      return;
    }

    cartHeader.textContent = `购物车商品 (${cartItems.length})`;
    checkoutBtn.disabled = false;

    cartItems.forEach(item => {
      const cartItem = document.createElement('div');
      cartItem.className = 'cart-item';
      cartItem.dataset.cartId = item.cartId;
      cartItem.dataset.goodsId = item.goodsId;
      cartItem.dataset.stock = item.stock;

      cartItem.innerHTML = `
                <div class="item-image">
                    <i class="fas fa-box-open" style="font-size: 48px; color: #ccc;"></i>
                </div>
                <div class="item-details">
                    <div class="item-info">
                        <h3 class="item-name">${item.name}</h3>
                        <div class="item-category">${item.category}</div>
                        <div class="item-stock">库存: ${item.stock}件</div>
                    </div>
                    <div class="item-actions">
                        <div class="item-price">¥${item.price.toFixed(2)}</div>
                        <div class="item-quantity">
                            <button class="quantity-btn decrease-btn">-</button>
                            <input type="number" class="quantity-input" value="${item.quantity}" min="1" max="${item.stock}">
                            <button class="quantity-btn increase-btn">+</button>
                        </div>
                    </div>
                </div>
                <button class="remove-btn">
                    <i class="fas fa-times"></i>
                </button>
            `;

      cartItemsContainer.appendChild(cartItem);

      // 绑定事件监听器
      const decreaseBtn = cartItem.querySelector('.decrease-btn');
      const increaseBtn = cartItem.querySelector('.increase-btn');
      const quantityInput = cartItem.querySelector('.quantity-input');
      const removeBtn = cartItem.querySelector('.remove-btn');

      decreaseBtn.addEventListener('click', () => {
        updateQuantity(item.cartId, parseInt(quantityInput.value) - 1);
      });

      increaseBtn.addEventListener('click', () => {
        updateQuantity(item.cartId, parseInt(quantityInput.value) + 1);
      });

      quantityInput.addEventListener('change', () => {
        let value = parseInt(quantityInput.value);
        if (isNaN(value) || value < 1) {
          value = 1;
        } else if (value > item.stock) {
          value = item.stock;
          showNotification('数量不能超过库存', true);
        }
        quantityInput.value = value;
        updateQuantity(item.cartId, value);
      });

      removeBtn.addEventListener('click', () => {
        removeCartItem(item.cartId);
      });
    });
  }

  // 更新购物车摘要
  function updateCartSummary(cartItems) {
    let subtotal = 0;

    cartItems.forEach(item => {
      subtotal += item.price * item.quantity;
    });

    subtotalElement.textContent = `¥${subtotal.toFixed(2)}`;
    totalElement.textContent = `¥${subtotal.toFixed(2)}`;
  }

  // 更新购物车数量
  function updateCartCount(count) {
    cartCount.textContent = count;
  }

  // 更新商品数量
  function updateQuantity(cartId, newQuantity) {
    // 检查库存
    const cartItem = document.querySelector(`.cart-item[data-cart-id="${cartId}"]`);
    const stock = parseInt(cartItem.dataset.stock);

    if (newQuantity < 1) newQuantity = 1;
    if (newQuantity > stock) {
      newQuantity = stock;
      showNotification('数量不能超过库存', true);
    }

    // 调用后端API更新购物车
    fetch(`${API_BASE_URL}/shoppingCart/update`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        sId: cartId,
        sQuantity: newQuantity
      })
    })
            .then(response => {
              if (!response.ok) {
                throw new Error('更新购物车失败');
              }
              return response.text();
            })
            .then(message => {
              showNotification('购物车已更新');
              // 刷新购物车数据
              fetchCartData();
            })
            .catch(error => {
              console.error('更新购物车失败:', error);
              showNotification('更新购物车失败', true);
              // 刷新购物车数据恢复状态
              fetchCartData();
            });
  }

  // 移除购物车商品
  function removeCartItem(cartId) {
    fetch(`${API_BASE_URL}/shoppingCart/remove/${cartId}`, {
      method: 'DELETE'
    })
            .then(response => {
              if (!response.ok) {
                throw new Error('移除商品失败');
              }
              return response.text();
            })
            .then(message => {
              showNotification('商品已从购物车移除');
              // 刷新购物车数据
              fetchCartData();
            })
            .catch(error => {
              console.error('移除商品失败:', error);
              showNotification('移除商品失败', true);
            });
  }

  // 清空购物车
  function clearCart() {
    if (!userInfo) return;

    if (!confirm('确定要清空购物车吗？')) return;

    fetch(`${API_BASE_URL}/shoppingCart/clear/${userInfo.userId}`, {
      method: 'DELETE'
    })
            .then(response => {
              if (!response.ok) {
                throw new Error('清空购物车失败');
              }
              return response.text();
            })
            .then(message => {
              showNotification('购物车已清空');
              // 刷新购物车数据
              fetchCartData();
            })
            .catch(error => {
              console.error('清空购物车失败:', error);
              showNotification('清空购物车失败', true);
            });
  }

  // 结算购物车
  function checkout() {
    // 这里可以添加结算逻辑
    alert('结算功能将在后续实现');
  }

  // 显示通知
  function showNotification(message, isError = false) {
    notification.textContent = message;
    notification.className = 'notification';

    if (isError) {
      notification.classList.add('error');
    }

    // 显示通知
    notification.style.display = 'block';

    setTimeout(() => {
      notification.style.display = 'none';
    }, 3000);
  }
</script>
</body>
</html>